package com.quectel.core.module.partyeducationtraining.service.impl;


import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.partyeducationtraining.dao.TrainingItemDao;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingItemDto;
import com.quectel.core.module.partyeducationtraining.entity.TrainingItemEntity;
import com.quectel.core.module.partyeducationtraining.service.TrainingItemService;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2022/05/07 16:40
 */
@DubboService
public class TrainingItemServiceImpl implements TrainingItemService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TrainingItemServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> TRAINING_ITEM_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "TRAINING_ITEM_CACHE_BY_ID:%d", id);

    @Autowired
    private TrainingItemDao trainingItemDao;
    @Autowired
    private TrainingService trainingService;

    @Override
    public TrainingItemDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                TRAINING_ITEM_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public TrainingItemDto selectById(Long id) {
        TrainingItemEntity entity = trainingItemDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, TrainingItemDto.class));
    }

    @Override
    public List<TrainingItemDto> queryList(Map<String, Object> params) {
        List<TrainingItemEntity> list = trainingItemDao.queryList(params);
        List<TrainingItemDto> result = CopyUtils.copyList(list, TrainingItemDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private TrainingItemDto paddingField(TrainingItemDto dto) {
        if (dto != null) {
            TrainingDto trainingDto = trainingService.selectCacheById(dto.getTrainingId());
            if (trainingDto != null) {
                // 课程名称
                dto.setTrainingName(trainingDto.getName());
                // 课程总培训人数
                dto.setTrainingPersonCount(trainingDto.getTrainingPersonCount());
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return trainingItemDao.queryTotal(params);
    }

    @Override
    @Lock(lockExpresses = RedisLockConstants.TRAINING_LOCK + "#{#dto.trainingId}")
    public Long save(TrainingItemDto dto) {
        TrainingItemEntity entity = CopyUtils.copyObj(dto, TrainingItemEntity.class);
        entity.setId(Snowflake.nextId());
        trainingItemDao.insert(entity);
        changeTrainingItemCount(dto.getTrainingId(), 1);
        return entity.getId();
    }

    /**
     * 关联更新课时数
     *
     * @param trainingId 课程id
     * @param c          计数
     */
    private void changeTrainingItemCount(Long trainingId, int c) {
        TrainingDto dbTrainingDto = trainingService.selectById(trainingId);
        TrainingDto newlyDto = new TrainingDto();
        newlyDto.setId(dbTrainingDto.getId());
        newlyDto.setTrainingItemCount(dbTrainingDto.getTrainingItemCount() == null
                ? c : dbTrainingDto.getTrainingItemCount() + c);
        trainingService.updateById(newlyDto);
    }

    @Override
    public void updateById(TrainingItemDto dto) {
        TrainingItemEntity entity = CopyUtils.copyObj(dto, TrainingItemEntity.class);
        trainingItemDao.updateById(entity);
        CacheKit.invalidRedisCache(TRAINING_ITEM_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(TrainingItemDto dto) {
        TrainingItemEntity entity = CopyUtils.copyObj(dto, TrainingItemEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, trainingItemDao);

        CacheKit.invalidRedisCache(TRAINING_ITEM_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        trainingItemDao.deleteById(id);

        CacheKit.invalidRedisCache(TRAINING_ITEM_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            TrainingItemDto trainingItemDto = selectCacheById(id);
            if (trainingItemDto != null) {
                changeTrainingItemCount(trainingItemDto.getTrainingId(), -1);
            }
            deleteById(id);
        }
    }
}
